package com.demo.task.remote.interceptor

import com.demo.task.MainApplication
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * 拦截器：模拟接口数据
 */
class FakeApiInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val json = getJson()
        return if (!chain.request().url.toString().contains("test2"))
            chain.proceed(chain.request())
        else Response.Builder()
            .code(200)
            .addHeader("Content-Type", "application/json")
            .body(json.toResponseBody("application/json".toMediaTypeOrNull()))
            .message(json)
            .request(chain.request())
            .protocol(Protocol.HTTP_2)
            .build()
    }

    private fun getJson(jsonName: String = "data.json"): String {
        val sb = StringBuilder()
        return try {
            val jsonFile = MainApplication.instance.assets.open(jsonName)
            val isr = InputStreamReader(jsonFile)
            val br = BufferedReader(isr)
            var line: String?
            while (br.readLine().also { line = it } != null) {
                sb.append(line)
            }
            br.close()
            isr.close()
            sb.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
    }
}